import {Sequelize, DataTypes} from 'sequelize';
import constant from '../common/constant.js';

const {MYSQL_DB_NAME, MYSQL_USER, MYSQL_PASS, MYSQL_HOST, MYSQL_PORT} = constant;
const sequelize = new Sequelize(MYSQL_DB_NAME, MYSQL_USER, MYSQL_PASS, {
  host: MYSQL_HOST,
  port: MYSQL_PORT,

  dialect: 'mysql',
  dialectOptions: {
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci',
    supportBigNumbers: true,
    bigNumberStrings: true,
    dateStrings: true, //将Date格式化日期字符串
    typeCast: true
  },
  define: {
    underscored: true,// 数据库启用下划线命名法,
    timestamps: true,
    freezeTableName: true,
  },
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  timezone: '+08:00',
});
sequelize.authenticate().then(() => {
  console.log('数据库连接成功');
}).catch(err => {
  console.error('数据库连接失败', err);
});

// 原始查询的结果映射函数，将下划线字段名转换为驼峰式
function mapKeysToCamelCase(rows) {
  return rows.map(row => {
    const camelCaseRow = {};
    for (const key in row) {
      if (Object.prototype.hasOwnProperty.call(row, key)) {
        // 将下划线字段名转换为驼峰式
        const camelCaseKey = key.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
        camelCaseRow[camelCaseKey] = row[key];
      }
    }
    return camelCaseRow;
  });
}

/*// 设置查询结果字段名的转换规则
sequelize.options.quoteIdentifiers = false; // 取消标识符的引号
sequelize.options.fieldMap = {}; // 字段映射对象*/

// 在查询之前设置字段名转换规则
sequelize.addHook('beforeFind', (options) => {
  if (options.type === 'SELECT') {
    options.fieldMap = options.fieldMap || {};
    options.fieldMap = Object.keys(options.model.rawAttributes).reduce((fieldMap, fieldName) => {
      const field = options.model.rawAttributes[fieldName];
      fieldMap[field.fieldName] = field.fieldName;
      fieldMap[field.fieldName] = field.fieldName.replace(/_(\w)/g, (all, letter) => letter.toUpperCase());
      return fieldMap;
    }, {});
  }
});

export {
  sequelize,
  mapKeysToCamelCase,
}
